package com.yst.webplugin.component;

import com.yst.web.common.BusinessException;
import com.yst.web.common.Result;
import com.yst.web.common.ResultCode;
import com.yst.webplugin.exception.ExceptionNotLogin;
import com.yst.webplugin.exception.ExceptionParam;
import com.yst.webplugin.exception.ExceptionPermissionInsufficient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler({Exception.class, Throwable.class})
    public Result<Object> handleException(Exception e){
        log.error(e.getMessage(),e);
        return new Result<>().setCode(ResultCode.ERROR_UNKNOWN);
    }

    @ExceptionHandler({ExceptionNotLogin.class})
    public Result<Object> handleBusinessException(ExceptionNotLogin e){
        log.error(e.getMessage(),e);
        return new Result<>().setCode(ResultCode.ERROR_NEED_LOGIN);
    }

    @ExceptionHandler({ExceptionParam.class})
    public Result<Object> handleParamException(ExceptionParam e){
        log.error(e.getMessage());
        return new Result<>().setCode(ResultCode.ERROR_BUSINESS)
                .setMsg(e.getMessage());
    }

    @ExceptionHandler({ExceptionPermissionInsufficient.class})
    public Result<Object> handleParamException(ExceptionPermissionInsufficient e){
        log.error(e.getMessage());
        return new Result<>().setCode(ResultCode.ERROR_PERMISSIONS_INSUFFICIENT);
    }

    @ExceptionHandler({BusinessException.class})
    public Result<Object> handleBusinessException(BusinessException e){
        if (e.getCode()==ResultCode.ERROR_UNKNOWN.code)
        {
            log.error(e.getMessage(),e);
        }
        else {
            log.warn(e.getMessage());
        }

        return new Result<>().setCode(e.getCode()).setMsg(e.getMessage());
    }
}
